﻿import torch
import torch.nn as nn


class BasicBlock(nn.Module):  # 定义34的残差结构
    expansion = 1

    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(
            in_channels=in_channel,
            out_channels=out_channel,
            kernel_size=3,
            padding=1,
            stride=stride,
            bias=False,
        )
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.relu = nn.ReLU()

        self.conv2 = nn.Conv2d(
            in_channels=out_channel,
            out_channels=out_channel,
            kernel_size=3,
            padding=1,
            stride=1,
            bias=False,
        )
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.downsample = downsample

    def forward(self, x):
        identity = x
        if (
            self.downsample is not None
        ):  # 如果下采样层不为空，则堆输入进行下采样得到捷径分支的输出
            identity = self.downsample(x)

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out += identity  # 将输出与残差连接相加
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4  # 指定扩张因子为4，主分支的卷积核个数最后一层会变为第一层的四倍

    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(Bottleneck, self)._init_()
        # 定义第一个1*1的卷积层用于压缩我们的通道数
        self.conv1 = nn.Conv2d(
            in_channels=in_channel,
            out_channels=out_channel,
            kernel_size=1,
            stride=1,
            bias=False,
        )
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.conv2 = nn.Conv2d(
            in_channels=out_channel,
            out_channels=out_channel,
            kernel_size=3,
            stride=stride,
            bias=False,
            padding=1,
        )
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.conv3 = nn.Conv2d(
            in_channels=out_channel,
            out_channels=out_channel * self.expansion,
            kernel_size=1,
            stride=1,
            bias=False,
        )
        self.bn3 = nn.BatchNorm2d(out_channel * self.expansion)
        self.relu = nn.ReLU()
        self.downsample = (
            downsample  # 下采样层，如果输入和输出的尺寸不匹配，那么我们会对它进行下采样
        )

    def forward(self, x):
        identity = x  # 保存输入的数据，便于进行残差链接
        if self.downsample is not None:
            identity = self.downsample(x)

        out = self.conv1(x)  # 第一个卷积改变通道数的大小通道数的压缩
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)  # 第二个卷积核大小为3*3
        out = self.bn2(out)
        out = self.relu(out)
        out = self.conv3(out)  # 第三个卷积将通道数恢复
        out = self.bn3(out)
        out += identity  # 将主分支与捷径分支相加
        out = self.relu(out)
        return out  #


class ResNet(nn.Module):  # 络的框架部分
    def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
        super()._init_()
        self.include_top = include_top  # 分类头
        self.in_channel = 64
        self.conv1 = nn.Conv2d(
            3, self.in_channel, kernel_size=7, stride=2, bias=False, padding=3
        )
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU()
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(
            block, 64, blocks_num[0]
        )  # 创建四个残差层，分别对应resnet的四个stage
        self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
        if self.include_top:
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
            self.fc = nn.Linear(512 * block.expansion, num_classes)
        for m in self.modules():  # 如果是卷积层
            if isinstance(m, nn.Conv2d):
                # 使用kaiming初始化
                nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")

    def _make_layer(self, block, channel, block_num, stride=1):  # 创建一个残差层
        # block为对应网络深度来选取
        # channel为残差结构中第一个卷积层的个数
        # block_num该层包含多少个残差结构
        downsample = None
        # 如果步长不为1或者输入通道数不等于残差块的输入通道数*扩张因子，则需要进行下采样
        if stride != 1 or self.in_channel != channel * block.expansion:
            # 对于layer1的构建使用resnet18不满足条件会跳过下采样的操作
            # 对于resnet50101满足条件会进行下采样操作通道数由64变为256需要对齐便于进行残差连接
            downsample = nn.Sequential(
                nn.Conv2d(
                    self.in_channel,
                    channel * block.expansion,
                    kernel_size=1,
                    stride=stride,
                    bias=False,
                ),
                nn.BatchNorm2d(channel * block.expansion),
            )
            layers = []  # 定义一个空列表用于存储残差结构
        layers.append(
            block(self.in_channel, channel, downsample=downsample, stride=stride)
        )

        self.in_channel = channel * block.expansion

        for _ in range(1, block_num):
            layers.append(block(self.in_channel, channel))

        return nn.Sequential()

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)  # 通过3*3的最大池化
        # 将输出输入到layer1即conv2对应的一系列残差结构
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        if self.include_top:
            x = self.avgpool(x)
            x = torch.flatten(x, 1)
            x = self.fc(x)
        return x

    def resnet18(num_classes=1000, include_top=True, pretrained=False):
        return ResNet(
            BasicBlock, [2, 2, 2, 2], num_classes=num_classes, include_top=include_top
        )

    def resnet34(num_classes=1000, include_top=True, pretrained=False):
        return ResNet(
            BasicBlock, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top
        )

    def resnet50(num_classes=1000, include_top=True, pretrained=False):
        return ResNet(
            Bottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top
        )

    def resnet101(num_classes=1000, include_top=True, pretrained=False):
        return ResNet(
            Bottleneck, [3, 4, 23, 3], num_classes=num_classes, include_top=include_top
        )
